package simple.utils.concurrent;

import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;
import java.util.concurrent.atomic.AtomicLong;

/**
 * Created with IntelliJ IDEA.
 * User: rehak
 * Date: 11/26/13
 * Time: 1:54 PM
 * To change this template use File | Settings | File Templates.
 */
public class Counter<E> {

    private ConcurrentMap<E, AtomicLong> cnts = new ConcurrentHashMap<>();

    public void add(E object, int count) {
        AtomicLong cnt = new AtomicLong(0);
        AtomicLong old = cnts.putIfAbsent(object, cnt);
        if (old != null) {
            cnt = old;
        }
        cnt.addAndGet(count);
    }

    public Set<E> getObjects() {
        return cnts.keySet();
    }

    public long getCnt(E obj) {
        if (!cnts.containsKey(obj)) {
            return 0;
        }
        return cnts.get(obj).get();
    }

}
